package com.snails.net.retrofit.interceptor;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.annotation.RawRes;

import com.snails.net.SnailsNet;
import com.snails.net.utils.FileUtil;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 自定义Json模拟网络请求，进行快速开发
 * @author  lawrence
 * @date    2019-04-15
 * 使用注意：
 * 1、需要先初始化SnailsNet,[SnailsNet.instance().init()]
 * 2、测试JSON文件存储路径，res => raw
 */
public class TestJsonInterceptor implements Interceptor {
    private final String testUrl;
    private final @RawRes int rawId;

    /**
     * 构造器
     * @param testUrl   模拟返回数据，url地址
     * @param rawId     本地返回json数据的资源id,[注意：路径为 res->raw]
     */
    public TestJsonInterceptor(String testUrl, @RawRes int rawId) {
        this.testUrl = testUrl;
        this.rawId = rawId;
    }

    private Response getResponse(Chain chain, String json) {
        return new Response.Builder()
                .code(200)
                .addHeader("Content-Type", "application/json")
                .body(ResponseBody.create(MediaType.parse("application/json"), json))
                .message("OK")
                .request(chain.request())
                .protocol(Protocol.HTTP_1_1)
                .build();
    }

    private Response testResponse(Chain chain, @RawRes int rawId) {
        final Context appCtx = SnailsNet.instance().getCtx();
        final String json = FileUtil.getRawFile(appCtx, rawId);
        return getResponse(chain, json);
    }

    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        final String url = chain.request().url().toString();
        if (url.contains(testUrl)) {
            return testResponse(chain, rawId);
        }
        return chain.proceed(chain.request());
    }
}
